<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
      <!--字典数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" size="small" clearable style="width: 150px"/>
        </el-form-item>
        <el-form-item label="字典编码" prop="dictCode">
          <el-input v-model="queryParams.dictCode" placeholder="请输入字典编码" size="small" clearable style="width: 150px"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="queryParams.remark" placeholder="请输入备注" size="small" clearable style="width: 150px"/>
        </el-form-item>
    <!--    <el-form-item label="字典类型" prop="dictTypeCode">
          <el-select @change="handleQuery" v-model="queryParams.dictTypeCode" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in dictTypeOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
          </el-select>
        </el-form-item>-->
        <el-form-item label="字典状态" prop="statusCode">
          <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['saveSystemDict']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增字典</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['resetSystemDictCache']"  icon="el-icon-refresh" size="mini" @click="resetSystemDictCache">刷新缓存</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="queryOneLevelSystemDictPageResList" :columns="columns"></right-toolbar>
      </el-row>

        <el-table ref="multipleTable" :stripe="true" @row-click="clickRow" v-loading="loading" :data="dataList"  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column label="字典名称" sortable='custom' align="left" prop="dictName"/>
          <el-table-column label="字典编码" sortable='custom' align="left" prop="dictCode"/>
          <el-table-column label="字典类型" align="left" prop="dictTypeName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.dictTypeColor">{{scope.row.dictTypeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="字典状态" align="left" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" sortable='custom' align="center" prop="remark"/>
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="排序" sortable='custom' align="center" prop="sort"  width="100"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSystemDict']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" v-if="scope.row.dictTypeCode!=='SYSTEM_DICT'" type="text" v-hasPermi="['deleteSystemDict']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryOneLevelSystemDictPageResList"/>
      </el-col>
    </el-row>


    <el-row :gutter="20" v-if="childrenDataTable">
      <el-col>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" :disabled="handleChildrenAddUse"  v-hasPermi="['saveSystemDict']"  icon="el-icon-plus" size="mini" @click="handleChildrenAdd">新增子项</el-button>
          </el-col>
        </el-row>
        <el-table ref="childrenMultipleTable" :stripe="true" v-loading="childrenLoading" :data="childrenDataList" @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column label="字典名称" sortable='custom' align="left" prop="dictName"/>
          <el-table-column label="字典编码" sortable='custom' align="left" prop="dictCode"/>
          <el-table-column label="字典颜色" align="left" prop="dictColor" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.dictColor">{{scope.row.dictColor}}</span>
            </template>
          </el-table-column>
          <el-table-column label="字典类型" align="left" prop="dictTypeName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.dictTypeColor">{{scope.row.dictTypeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="字典状态" align="left" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" sortable='custom' align="center" prop="remark"/>
          <el-table-column label="排序" sortable='custom' align="center" prop="sort"  width="100"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSystemDict']" icon="el-icon-edit"  @click="handleChildrenUpdate(scope.row)">修改</el-button>
              <el-button size="mini" v-if="scope.row.dictTypeCode!=='SYSTEM_DICT'" type="text" v-hasPermi="['deleteSystemDict']" icon="el-icon-delete"  @click="handleChildrenDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="childrenTotal>0" :total="childrenTotal" :page.sync="queryChildrenParams.page" :limit.sync="queryChildrenParams.rows"
                    @pagination="queryOneLevelSystemDictPageResList"/>
      </el-col>
    </el-row>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.dictName" placeholder="请输入字典名称" maxlength="20" />
        </el-form-item>

        <el-form-item label="字典编码" prop="dictCode">
          <el-input :hide-required-asterisk="true" :disabled="form.dictTypeCode==='SYSTEM_DICT'" autocomplete="off" v-model="form.dictCode" placeholder="请输入字典编码" maxlength="10" />
        </el-form-item>

        <el-form-item label="字典状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入备注" maxlength="100" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改参数配置数据字典子项对话框 -->
    <el-dialog :title="childrenTitle" :visible.sync="childrenAddUpdateOpen" width="800px" append-to-body>
      <el-form ref="childrenForm" :model="childrenForm" :rules="addUpdateOpenRules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-col :span="23">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="childrenForm.dictName" placeholder="请输入字典名称" maxlength="20" />
          </el-col>
          <el-col :span="1">
            <el-color-picker v-model="childrenForm.dictColor"/>
          </el-col>
        </el-form-item>

        <el-form-item label="字典编码" prop="dictCode">
          <el-input :hide-required-asterisk="true" :disabled="childrenForm.dictTypeCode==='SYSTEM_DICT'" autocomplete="off" v-model="childrenForm.dictCode" placeholder="请输入字典编码" maxlength="10" />
        </el-form-item>

        <el-form-item label="字典状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="childrenForm.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="childrenForm.remark" placeholder="请输入备注" maxlength="100" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="childrenForm.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChildrenForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {queryOneLevelSystemDictPageResList, saveSystemDict, updateSystemDict,deleteSystemDictByDictId, queryChildrenSystemDictPageResList, resetSystemDictCache} from '@/api/system/systemDict'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  //默认查询参数
  let defaultQueryParams = {
    dictName: undefined,
    dictCode: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    remark: undefined,
    dictTypeCode: "BUSINESS_DICT",
    page: 1,
    rows: 10
  }
  export default {
    name: "systemDictAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 遮罩层
        childrenLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 子总条数
        childrenTotal: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // table表格数据
        childrenDataList: [],
        // table表格是否显示
        childrenDataTable:false,
        //子项新增按钮是否可用
        handleChildrenAddUse:false,
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 数据字典子项弹出层标题
        childrenTitle: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 是否显示数据字典子项新增修改弹出层
        childrenAddUpdateOpen: false,
        // 字典状态
        statusOptions: [],
        //字典类型
        dictTypeOptions:[],
        // 增加修改表单参数
        form: {},
        // 数据字典子项增加修改表单参数
        childrenForm: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //子级查询条件
        queryChildrenParams:{
          parentId:"-1",
          page: 1,
          rows: 10
        },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          dictName: [
            { required: true, message: "字典名称不能为空",trigger: "blur" },
          ],
          dictCode: [
            { required: true, message: "字典编码不能为空",trigger: "blur" },
          ],
          statusCode: [
            { required: true, message: "字典状态必须选择",trigger: "blur" }
          ],
          sort: [
            { required: true, message: "排序不能为空",trigger: "blur" },
          ]
        }
      }
    },
    created() {
      this.queryOneLevelSystemDictPageResList();
      this.initDict();
    },
    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
          //this.dictTypeOptions = JSON.parse(JSON.stringify(res.data['DICT_TYPE']));
        });
      },
      /** 查询一级字典列表 */
      queryOneLevelSystemDictPageResList() {
        this.loading = true
        queryOneLevelSystemDictPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },

      /** 查询子字典列表 */
      queryChildrenSystemDictPageResList() {
        this.childrenLoading = true;
        queryChildrenSystemDictPageResList(this.queryChildrenParams).then(response => {
          this.childrenDataList = response.data.records
          this.childrenTotal = response.data.total
          this.childrenLoading = false
        })
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.dictId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryOneLevelSystemDictPageResList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.childrenAddUpdateOpen = false;
        this.addUpdateOpen = true;
        this.title = "添加字典";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.childrenAddUpdateOpen = false;
        this.addUpdateOpen = true;
        this.title = "修改字典";
      },
      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.dictId !== undefined) {
              updateSystemDict(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryOneLevelSystemDictPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSystemDict(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryOneLevelSystemDictPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选字典?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const dictId={dictId:row.dictId}
          return deleteSystemDictByDictId(dictId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryOneLevelSystemDictPageResList();
        }).catch(function() {});
      },

      /** 刷新数据字典缓存操作 */
      resetSystemDictCache() {
        this.$confirm('是否确认刷新数据字典缓存?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          return resetSystemDictCache();
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryOneLevelSystemDictPageResList();
        }).catch(function() {});
      },

      /** 新增子项按钮操作 */
      handleChildrenAdd() {
        this.resetChildren();
        this.childrenForm = {
          sort: 1,
          parentId:this.queryChildrenParams.parentId
        };
        this.addUpdateOpen = false;
        this.childrenAddUpdateOpen = true;
        this.childrenTitle = "添加字典";
      },
      /** 修改子项按钮操作 */
      handleChildrenUpdate(row) {
        this.resetChildren();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.childrenForm = {...row};
        this.addUpdateOpen = false;
        this.childrenAddUpdateOpen = true;
        this.childrenTitle = "修改字典";
      },

      /** 删除按钮操作 */
      handleChildrenDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选字典?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const dictId={dictId:row.dictId}
          return deleteSystemDictByDictId(dictId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryChildrenSystemDictPageResList();
        }).catch(function() {});
      },

      /** 提交数据字典子项保存或修改按钮 */
      submitChildrenForm: function() {
        this.$refs["childrenForm"].validate(valid => {
          if (valid) {
            if (this.childrenForm.dictId !== undefined) {
              updateSystemDict(this.childrenForm).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryChildrenSystemDictPageResList();
                this.childrenAddUpdateOpen = false
              });
            } else {
              saveSystemDict(this.childrenForm).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryChildrenSystemDictPageResList();
                this.childrenAddUpdateOpen = false
              });
            }
          }
        });
      },

      //点击行触发事件
      clickRow(row) {
        this.queryChildrenParams.parentId = row.dictId;
        this.$refs.multipleTable.toggleRowSelection(row);
        this.childrenDataTable = true;
        this.handleChildrenAddUse = row.dictTypeCode==='SYSTEM_DICT'
        this.queryChildrenSystemDictPageResList();
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.childrenDataTable=false;
        this.queryOneLevelSystemDictPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.childrenDataTable=false;
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
        this.childrenAddUpdateOpen = false
      },

      // 是否允许选择
      checkSelectable(row) {
        return row.dictTypeCode!=='SYSTEM_DICT'
      },
      // 表单重置
      reset() {
        this.form = {
          parentId:"-1",
          dictId: undefined,
          dictName: undefined,
          dictCode: undefined,
          dictColor: undefined,
          sort: 1,
          remark: undefined,
          statusOptions: []
        };
        this.resetForm('form')
      },
      // 表单重置
      resetChildren() {
        this.childrenForm = {
          dictId: undefined,
          dictName: undefined,
          dictCode: undefined,
          dictColor: undefined,
          sort: 1,
          remark: undefined,
          statusOptions: []
        };
        this.resetForm('childrenForm')
      }
    }
  }
</script>
